<template>
    <view v-if="state.show" class="real_name_container">
        <view class="upload_card">
            <view class="label w_100">请上传证件照（必填）</view>
            <view class="btn_container">
                <view class="left" @click="onChooseMedia(1)">
                    <image v-if="form.idcardFrontier" class="code_img" :src="form.idcardFrontier" />
                    <view v-else class="btn">
                        <image class="btn_icon" :src="addIcon" />
                        <view class="btn_text">*请上传身份证人像面</view>
                    </view>
                </view>
                <view class="right" @click="onChooseMedia(2)">
                    <image v-if="form.idcardBack" class="code_img" :src="form.idcardBack" />
                    <view v-else class="btn">
                        <image class="btn_icon" :src="addIcon" />
                        <view class="btn_text">*请上传身份证国徽面</view>
                    </view>
                </view>
            </view>
        </view>
        <view class="item">
            <view class="label">*姓名</view>
            <view class="content">
                <input
                    v-model="form.realName"
                    class="input"
                    placeholder-class="placeholder"
                    :maxlength="15"
                    :cursor-spacing="75"
                    placeholder="请填写您的真实姓名"
                    :disabled="authenticated" />
            </view>
        </view>
        <view class="item">
            <view class="label">*身份证号</view>
            <view class="content">
                <input
                    v-model="form.idcardNo"
                    type="idcard"
                    class="input"
                    placeholder-class="placeholder"
                    :maxlength="18"
                    :cursor-spacing="75"
                    placeholder="请填写您的身份证号"
                    :disabled="authenticated" />
            </view>
        </view>
        <view v-if="!authenticated" class="footer_btn">
            <view @click="onSave" class="footer_btn_text">保存</view>
        </view>
        <Loading />
    </view>
    <!-- 隐私监听 -->
    <el-privacy-listener-popup></el-privacy-listener-popup>
</template>

<script setup>
import Loading from '@/components/el-loading';
import request from '@/request';
import router from '@/router';
import { getImgOssUrl, uploadeFile } from '@/commons/utils.js';
import { onShow } from '@dcloudio/uni-app';
import { reactive } from 'vue';

const props = defineProps({
    status: { type: String }
});
const addIcon = getImgOssUrl('/ui-prod-2.0.0/add_icon_2.0.png');
const authenticated = props.status === 'authenticated'; // 是否已认证
const state = reactive({
    show: false
});

const form = reactive({
    idcardFrontier: '', // 身份证人像面
    idcardBack: '', // 身份证国徽面
    realName: '', // 姓名
    idcardNo: '' // 身份证号
});

const onShowToast = msg => uni.showToast({ title: msg, icon: 'none' });

// 转base64
const onBase64 = tempFilePath => {
    return new Promise((resolve, reject) => {
        uni.getFileSystemManager().readFile({
            filePath: tempFilePath, //要读取的文件的路径 (本地路径)
            encoding: 'base64', //指定读取文件的字符编码，如果不传 encoding，则以 ArrayBuffer 格式读取文件的二进制内容
            success: async res2 => {
                const ocrParams = {
                    base64Str: res2.data // 图片base64
                    // channel: '',
                    // ocrTransSerialNostring: ''
                };
                const result = await request('idcardOCRServ', ocrParams);
                resolve(result);
            }
        });
    });
};

// 选择图片/拍照
const onChooseMedia = type => {
    if (authenticated) return;
    uni.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        success: async res1 => {
            const { tempFilePath, size } = res1.tempFiles[0];
            if (size * 1.33 > 4 * 1024 * 1024) {
                onShowToast('图片大小不能超过4MB');
                return;
            }
            // 支持类型
            const supportType = 'jpg、jpeg、png、bmp';
            const fileType = tempFilePath.substring(tempFilePath.lastIndexOf('.') + 1);
            if (!supportType.includes(fileType)) {
                onShowToast(`请上传${supportType}格式的图片`);
                return;
            }
            const [result1, result2] = await Promise.all([
                onBase64(tempFilePath),
                uploadeFile({ filePath: tempFilePath, timeout: 150000 })
            ]);
            if (type === 1) {
                form.realName = result1.data.name;
                form.idcardNo = result1.data.idNumber;
                form.idcardFrontier = result2.data.url;
            } else {
                form.idcardBack = result2.data.url;
            }
        }
    });
};

const onValidate = () => {
    const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!form.idcardFrontier) {
        onShowToast('请上传身份证人像面');
        return false;
    }
    if (!form.idcardBack) {
        onShowToast('请上传身份证国徽面');
        return false;
    }
    if (!form.realName) {
        onShowToast('请输入姓名');
        return false;
    }
    if (!form.idcardNo) {
        onShowToast('请输入身份证号');
        return false;
    }
    if (!reg.test(form.idcardNo)) {
        onShowToast('请输入正确的身份证号');
        return false;
    }
    return true;
};

// 获取实名认证信息
const getRealNameInfo = async () => {
    const { data } = await request('getRealNameServ');
    form.idcardBack = data.idImgReverseSide;
    form.idcardFrontier = data.idImgFrontSide;
    form.realName = data.name;
    form.idcardNo = data.idNo;
    state.show = true;
};

// 保存实名认证信息
const onSave = async () => {
    if (!onValidate()) return;
    await request('saveRealNameServ', form);
    router.back();
};

onShow(() => {
    if (authenticated) {
        getRealNameInfo();
    } else {
        state.show = true;
    }
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
